// 导入食物、蛇
import Food from "./food.js"
import Snake from "./snake.js"
export default class Game {
    constructor(ele,score) {
        //接受地图
        this.map = document.querySelector(ele)
        //获取记分牌
        this.score = document.querySelector(score)
        //创建食物
        this.food = new Food(this.map)
        //创建蛇
        this.snake = new Snake(this.map)
        
        //准备一个级别
        this.level = 3  //2 3 4 5
        //准备一个变量接受定时器返回值
        this.timer = 0
        this.change()

        //准备一个变量用作 计数
        this.count = 0
        this.sum=0
    }
    //1.开始游戏
    start() {
        this.timer = setInterval(() => {

        //让蛇移动一次
        this.snake.move()

        //判断是不是吃到食物
        if(this.snake.isEat(this.food)){
            this.updateScore()
            //加一节
            this.snake.creHead()
            //食物换个位置
            this.food.newFood()
        }

        //判断是不是撞了
        if(this.snake.isDie()){
            window.alert('game over')
            clearInterval(this.timer)
        }
        }, 500 / this.level)
    }
    //2.暂停游戏
    stop(){
        clearInterval(this.timer)
    }
    //3.重新开始
    restart(){
        this.sum=0;
        window.location.reload()
    }
    //4.修改方向
    change(){
        document.addEventListener('keydown',e=>{
            e = e ||window.event
            const code = e.keyCode || e.which
            switch(code){
                case 37: this.snake.direction = 'left';break
                case 38: this.snake.direction = 'top';break
                case 39: this.snake.direction = 'right';break
                case 40: this.snake.direction = 'bottom';break
            }
        })
    }
    //5.更改记分牌
    updateScore(){
        //计数器++
        this.count++
        // console.log( this.count*90 +this.level*10);
        this.sum+=( 90 +this.level*10)
        //根据count 数据书写 input 文本内容
        this.score.value =this.sum
        //判断，当吃到的食物到达一定数量的时候，level++
        if(this.count % 15 === 0){
            this.level++
            this.stop()
            this.start()
        }
    }
}